package edu.chl.jadetalk.business.upload;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;
import javax.ejb.Startup;

/**
 * Simple memory cache for images.
 * @author Daniel
 */
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@Startup
public class ImageCache implements ImageCacheLocal {

    private ConcurrentMap<String, Byte[]> cache;
    
    @PostConstruct
    private void init() {
        cache = new ConcurrentHashMap<String, Byte[]>();
    }
    
    @Override
    public Byte[] getImage(String filename) {
        Logger.getAnonymousLogger().log(Level.INFO, String.format("ImageCache.getImage('%s') | isNull?: %s.", filename, cache.get(filename) == null ? "Yes" : "No"));
        return cache.get(filename);
    }

    @Override
    public void putImage(String filename, byte[] image) {
        Logger.getAnonymousLogger().log(Level.INFO, String.format("ImageCache.putImage('%s', byte[%d])", filename, image.length));
        Byte[] bytes = new Byte[image.length];
        for (int i = 0; i < image.length; i++) {
            bytes[i] = Byte.valueOf(image[i]);
        }
        cache.put(filename, bytes);
    }
}
